<?php
declare(strict_types=1);

namespace App;

use Swoole\Thread\Map;
use Swoole\Thread;

class GlobalData
{
    public static ?Map $map = null;

    public static function init(?callable $callBacks = null): array
    {
        if (is_null(self::$map))  self::$map = new Map();

        if (!is_null($callBacks)) $callBacks(self::$map);

        return [self::$map];
    }


    public static function getMap(): ?Map
    {
        // 如果没有map，初始化
        GlobalData::init();

        if (Runtime::isMainThread()) {
            return self::$map;
        }
        return Thread::getArguments()[0] ?? null;
    }


    public static function set(string $key, mixed $value): void
    {
        $map = self::getMap();
        if (!is_null($map)) {
            $map[$key] = $value;
        }
    }

    public static function get(string $key, mixed $default = null): mixed
    {
        $map = self::getMap();
        return is_null($map) ? $default : $map[$key] ?? $default;
    }


}